<?php

namespace App\Http\Controllers\Api;
use App\Blocks\ArticleBlock;
use App\Blocks\CrowdBlock;
use App\Blocks\TopicBlock;
use App\Http\Controllers\Controller;
use App\Http\Requests\Crowd;
use App\Libs\ResponseMessage;
use App\Models\CrowdClassify;
use App\Models\CrowdCollect;
use App\Models\CrowdMember;
use App\Models\Users;
use Illuminate\Http\Request;

class CrowdController extends Controller {
    /**
     * @api {get} /api/0.0.1/crowd/classify 获取群分类
     * @apiName getClassify
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群分类
     * @apiParam {Number} [pid=0] 分类上级id
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *          'id' : 1,       //分类ID
     *          'pid' : '0',    //分类上级ID
     *          'name' : '汽车', //分类名称
     *          'icon': 'http://community.img.guoxiaoge.cn/qiche.png', //分类icon
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdClassify(Request $request){
        $pid = (int)$request->get('pid', 0);
        $classify = CrowdClassify::where('pid', $pid)->whereNull('deleted_at')->get();
        // $array = ['id'=>0,'pid'=>0,'name'=>'全部','sort'=>0];
        // $classify = json_decode(json_encode($classify),true);
        // array_unshift($classify,$array);
        return response()->json(ResponseMessage::getInstance()->success($classify)->response());
    }

    /**
     * @api {post} /api/0.0.1/crowd/create 创建群
     * @apiName crowdCreate
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 创建群
     * @apiParam {String} name 群名称
     * @apiParam {String} headimgurl 群头像
     * @apiParam {Number} classify_id 群分类
     * @apiParam {Number} [is_free=0] 是否免费
     * @apiParam {Number} [charge=99.99] 费用
     * @apiParam {Number} [is_private=0] 公开还是私密
     * @apiParam {String} address 地址
     * @apiParam {String} introduce 简介
     * @apiParam {String} lat 经度
     * @apiParam {String} lon 纬度
     * @apiParam {String} token 登录凭证
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function createCrowd(Crowd $request){
        global $g_uid;
        $data = [
            'uid' => $g_uid,
            'name' => $request->get('name'),
            'headimgurl' => $request->get('headimgurl'),
            'classify_id' => $request->get('classify_id'),
            'address' => $request->get('address'),
            'lat' => $request->get('lat'),
            'lon' => $request->get('lon'),
            'introduce' => $request->get('introduce'),
            'is_free' => $request->get('is_free', 0),
            'is_private' => $request->get('is_private', 0),
            'charge' => (int)($request->get('charge', 0) * 100),
            'created_at' => date('Y-m-d H:i:s', time()),
            'tag_ids' => '',
            'member' => 1
        ];

        if($data['charge']>10000){
            $data['charge'] = 10000;
        }

//        if (preg_match("/^[x7f-xff]+$/",$data['name'])){
//            return 'aaa';
//        }else{
//            return 'bbb';
//        }
        if($data['is_free'] == 1){
            $data['charge'] = 0;
        }

        if($data['is_free'] == 0 && $data['charge'] <= 0){
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

        $crowdBlock = new CrowdBlock();

        $response = $crowdBlock->createCrowd($data);

        if($response){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

    }

    /**
     * @api {post} /api/0.0.1/crowd/update 更新群
     * @apiName crowdUpdate
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 修改群
     * @apiParam {Number} id 群ID
     * @apiParam {String} [name] 群名称
     * @apiParam {String} [headimgurl] 群头像
     * @apiParam {Number} [classify_id] 群分类
     * @apiParam {Number} [is_free] 是否免费
     * @apiParam {Number} [charge] 费用
     * @apiParam {Number} [is_private] 公开还是私密
     * @apiParam {String} [address] 地址
     * @apiParam {String} [lat] 经度
     * @apiParam {String} [lon] 纬度
     * @apiParam {String} [deleted_at] 删除时间
     * @apiParam {String} token 登录凭证
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function updateCrowd(Request $request){
        global $g_uid;
        if($request->has('id')){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $id = (int)$request->has('id');
        $updateField = [
            'name', 'headimgurl', 'classify_id', 'is_free', 'charge', 'is_private', 'address',
            'lat', 'lon'
        ];

        $updateData = [];
        foreach ($updateField as $field){
            if($request->has($field)){
                $updateData[$field] = $request->get($field);
            }
        }

        if(\App\Models\Crowd::where('id', $id)->where('uid', $g_uid)->update($updateData)){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }



    /**
     * @api {get} /api/0.0.1/crowd/list 获取群列表
     * @apiName getCrowd
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群列表
     * @apiParam {Number} [p_cid] 一级分类id
     * @apiParam {Number} [s_cid]  二级分类id
     * @apiParam {String} [search] 根据名字搜索
     * @apiParam {Number} [page=1] 分页
     * @apiParam {Number} [pageSize=20] 单页数量
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *          'id' : 1,                        //群ID
     *          'uid' : '0',                     //群主ID
     *          'name' : '汽车',                  //群名称
     *          'jg_im_gid' : 'xx'               //激光群
     *          'introduce' : '群简介',           //群简介
     *          'headimgurl' : 'http://xxxxx',   //群列表小图,
     *          'classify_id': 2,                //群分类ID 分类的二级id
     *          'tag_ids' : '1,2,3,4,5',         //群标签ID
     *          'grade' : 12,                    //群等级,
     *          'member' : 234,                  //群成员数量,
     *          'goods' : 4343,                  //群商品数量,
     *          'is_free': 1,                    //进去是否收费 1不收费，0收费
     *          'is_private': 1,                 //是否是私密群 1是，0不是
     *          'charge' : 'xx'                  //进群费用
     *          'classify_name': '分类',          //分类名称,
     *          'nick_name' : '辉仔',             //群主昵称,
     *          'created_at':'2018:10:11'        //创建时间
     *          'isJoin': '0'                   //是否加入该群,0:未加入,1:已加入
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowd(Request $request){
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 20);

        $searchKey = ['p_cid','s_cid', 'search'];
        $search = [];
        foreach ($searchKey as $key){
            if($request->has($key)){
                $search[$key] = $request->get($key);
            }
        }
        $crowdBlock = new CrowdBlock();
        global $g_uid;
        $list = $crowdBlock->getCrowdList($search, $page, $pageSize, $g_uid);

        return response()->json(ResponseMessage::getInstance()->success($list)->response());
    }

    /**
     * @api {get} /api/0.0.1/crowd/info 获取群详情
     * @apiName crowdInfo
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群详情
     * @apiParam {Number} id 群ID
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *          'crowd' : {
     *                  'id' : 1,                        //群ID
     *                  'uid' : '0',                     //群主ID
     *                  'name' : '汽车',                  //群名称
     *                  'detailed' : '详细简介',           //详细简介
     *                  'headimgurl' : 'http://xxxxx',   //群列表小图,
     *                  'classify_id': 2,                //群分类ID 分类的二级id
     *                  'tag_ids' : '1,2,3,4,5',         //群标签ID
     *                  'grade' : 12,                    //群等级,
     *                  'member' : 234,                  //群成员数量,
     *                  'goods' : 4343,                  //群商品数量,
     *                  'is_free': 1,                    //进去是否收费 1不收费，0收费
     *                  'is_private': 1,                 //是否是私密群 1是，0不是
     *                  'classify_name': '分类',          //分类名称,
     *                  'nick_name' : '辉仔',             //群主昵称,
     *                  'created_at':'2018:10:11'        //创建时间
     *                  'count': 'xx'                    //加入该群用户数
     *                  'articleCount': 'xx'             //文章数量
     *                  'login_user_is_admin' : 0        //我是否可以管理这个群
     *                  'userData':[                     //群用户信息
     *                      {
     *                          'headimgurl':[           //用户头像
     *                              'http://xx.jpg'
     *                              ....
     *                           ]
     *                          'nick_name':'xx'        //用户昵称
     *                      }
     *                  ]
     *          },
     *          'article' : [{
     *                  'id' : 1,                        //文章ID
     *                  'title': 'xxxxx',                //文章标题
     *                  'content' : 'xxxxx',             //文章内容
     *                  'headimgurl' : 'xxxxxx',         //问题小图
     *                  'comment' : 234,                 //评论数量
     *                  'useful' : 234,                  //点赞数量
     *                  'share' : 432,                   //分享次数
     *                  'views' : 231,                   //浏览量
     *                  'created_at': '2018-09-21 12:21:12' //创建时间
     *          }...]
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdInfo(Request $request){
        if (!$request->has('id')){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
        $id = (int)$request->get('id');
        $crowdBlock         = new CrowdBlock();
//        $topicBlock         = new TopicBlock();
        $articleBlock       = new ArticleBlock();

        $info = $crowdBlock->getCrowdInfo($id);
        $info->login_user_is_admin = 0;
//        $topic = $topicBlock->getTopicList(1, 10);
        $article = $articleBlock->getArticleList(['crowd_id' => $id], 1 , 3);

        global $g_uid;
        if($g_uid) {

            if($g_uid == $info->uid){
                $info->login_user_is_admin = 1;
            }

            $isJoin = CrowdMember::where('crowd_id', $id)->where('user_id', $g_uid)->whereNull('deleted_at')->count();
            $isCollect = CrowdCollect::where('crowd_id', $id)->where('user_id', $g_uid)->whereNull('deleted_at')->count();

            if ($info) {
                $info->is_join = $isJoin;
                $info->is_collect = $isCollect;
            }
        }


        return response()->json(ResponseMessage::getInstance()->success(['crowd' => $info, 'article' => $article])->response());
    }

    /**
     * @api {get} /api/0.0.1/crowd/info/jgid 根据极光群ID获取群详情
     * @apiName crowdInfoJgId
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 根据极光群ID获取群详情
     * @apiParam {Number} jg_im_gid 群ID
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : {
     *          'crowd' : {
     *                  'id' : 1,                        //群ID
     *                  'uid' : '0',                     //群主ID
     *                  'name' : '汽车',                  //群名称
     *                  'introduce' : '群简介',           //群简介
     *                  'headimgurl' : 'http://xxxxx',   //群列表小图,
     *                  'classify_id': 2,                //群分类ID 分类的二级id
     *                  'tag_ids' : '1,2,3,4,5',         //群标签ID
     *                  'grade' : 12,                    //群等级,
     *                  'member' : 234,                  //群成员数量,
     *                  'goods' : 4343,                  //群商品数量,
     *                  'is_free': 1,                    //进去是否收费 1不收费，0收费
     *                  'is_private': 1,                 //是否是私密群 1是，0不是
     *                  'classify_name': '分类',          //分类名称,
     *                  'nick_name' : '辉仔',             //群主昵称,
     *                  'created_at':'2018:10:11'        //创建时间
     *          },
     *      }
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdInfoByJgId(Request $request){
        $id = (int)$request->get('jg_im_gid');
        $crowdBlock         = new CrowdBlock();

        $info = $crowdBlock->getCrowdInfoByJgId($id);

        if($info) {
            $info->login_user_is_admin = 0;
            global $g_uid;
            $isJoin = CrowdMember::where('crowd_id', $info->id)->where('user_id', $g_uid)->whereNull('deleted_at')->count();
            $isCollect = CrowdCollect::where('crowd_id', $info->id)->where('user_id', $g_uid)->whereNull('deleted_at')->count();

            if($g_uid == $info->uid){
                $info->login_user_is_admin = 1;
            }
            if ($info) {
                $info->is_join = $isJoin;
                $info->is_collect = $isCollect;
            }
        }

        return response()->json(ResponseMessage::getInstance()->success($info)->response());
    }



    /**
     * @api {get} /api/0.0.1/crowd/article 获取群文章列表
     * @apiName getCrowdArticle
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群文章列表
     * @apiParam {Number} crowd_id 群ID
     * @apiParam {Number} [page=1] 分页
     * @apiParam {Number} [pageSize=20] 单页数量
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : [{
     *                  'id' : 1,                        //文章ID
     *                  'title': 'xxxxx',                //文章标题
     *                  'content' : 'xxxxx',             //文章内容
     *                  'headimgurl' : 'xxxxxx',         //问题小图
     *                  'comment' : 234,                 //评论数量
     *                  'useful' : 234,                  //点赞数量
     *                  'share' : 432,                   //分享次数
     *                  'created_at': '2018-09-21 12:21:12' //创建时间
     *
     *          }...]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdArticle(Request $request){
        $crowdId = (int)$request->get('crowd_id');
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 20);

        $articleBlock = new ArticleBlock();
        $article = $articleBlock->getArticleList(['crowd_id' => $crowdId], $page, $pageSize);
        return response()->json(ResponseMessage::getInstance()->success($article)->response());
    }

    /**
     * @api {get} /api/0.0.1/crowd/member 获取群成员列表
     * @apiName getCrowdMember
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群成员列表
     * @apiParam {Number} crowd_id 群ID
     * @apiParam {Number} [page=1] 分页
     * @apiParam {Number} [pageSize=20] 单页数量
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : [{
     *                  'id' : 1,                           //成员ID
     *                  'nick_name': 'xxxxx',               //成员昵称
     *                  'mobile' : 'xxxxx',                 //成员手机号
     *                  'headimgurl' : 'xxxxxx',            //成员头像
     *                  'updated_at': '2018-09-21 12:21:12' //创建时间
     *
     *          }...]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdMember(Request $request){
        $crowdId = (int)$request->get('crowd_id');
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 20);

        $crowdBlock = new CrowdBlock();
        $member = $crowdBlock->getCrowdMember($crowdId, $page, $pageSize);
        return response()->json(ResponseMessage::getInstance()->success($member)->response());
    }

    /**
     * @api {post} /api/0.0.1/crowd/remove/member 移出群成员
     * @apiName removeMember
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 移出群成员
     * @apiParam {Number} crowd_jg_id 群极光ID
     * @apiParam {Number} member_jg_id 群成员极光ID
     * @apiParam {String} token 登录标识
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : []
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function removeMember(Request $request){
        global $g_uid;
        $crowdJgId = $request->get('crowd_jg_id');

        $memberJgId = $request->get('member_jg_id');

        $crowdBlock = new CrowdBlock();

        $crowd = \App\Models\Crowd::where('jg_im_gid', $crowdJgId)->first();

        if(is_array($memberJgId)){

            $res = $crowdBlock->removeMember($memberJgId, $crowd->id, $g_uid);

        }else{
            $user = Users::where('jg_im_username', $memberJgId)->first();

            if(!$crowd || !$user){

                return response()->json(ResponseMessage::getInstance()->failed()->response());

            }
            $res = $crowdBlock->removeMember($user->id, $crowd->id, $g_uid);
        }



        if($res){

            return response()->json(ResponseMessage::getInstance()->success()->response());

        }else{

            return response()->json(ResponseMessage::getInstance()->failed()->response());

        }

    }

    /**
     * @api {get} /api/0.0.1/crowd/money/log 获取群收入支出流水
     * @apiName getMoneyLog
     * @apiGroup 群操作
     * @apiVersion 0.0.1
     * @apiDescription 获取群收入支出流水
     * @apiParam {Number} [crowd_id] 群ID
     * @apiParam {Number} [page=1] 分页
     * @apiParam {Number} [pageSize=20] 单页数量
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      'data'  : [{
     *                  'id' : 1,                           //ID
     *                  'money': 'xxxxx',                   //金额
     *                  'remark' : 'xxxxx',                 //备注
     *                  'created_at' : 'xxxxxx',            //创建时间,
     *                  'name' : 'xxxx'                     //群名称
     *
     *          }...]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function getCrowdFlowingWather(Request $request){
        global $g_uid;
        $crowdId = (int)$request->get('crowd_id', null);
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 20);

        $crowdBlock = new CrowdBlock();
        $log = $crowdBlock->getCrowdFlowingWather($crowdId, $g_uid, $page, $pageSize);
        return response()->json(ResponseMessage::getInstance()->success($log)->response());
    }
}